package com.foreknow.dao.impl;

import com.foreknow.bean.Admin;
import com.foreknow.dao.AdminDao;
import com.foreknow.db.DBManager;
import com.foreknow.db.JdbcTemplate;
import com.foreknow.mapping.EntityMapping;
import com.foreknow.mapping.MappingFactory;

import java.sql.Connection;
import java.util.List;

public class AdminDaoImpl extends BaseDao implements AdminDao {
    @Override
    public Admin login(String username, String password) {
        String sql = "select * from admin where username=? and password=?";
//        DBManager dbManager = DBManager.getInstance();
//        Connection conn = dbManager.getConnection();
        //JdbcTemplate jt =JdbcTemplate.getInstance();
//        this.setConnection(conn);
        //MappingFactory mappingFactory = MappingFactory.getInstance();
        EntityMapping mapping = mappingFactory.getMap(MappingFactory.ADMIN_MAPPING);
        List<Object> list = jdbcTemplate.query(sql,mapping,username,password);
        if (list.size() > 0){
            return (Admin) list.get(0);
        }
        return null;
    }

    @Override
    public List<Object> LikeQuery(String string) {
        String sql = "select * from admin where username like '%"+string+"%' ";
        MappingFactory mappingFactory = MappingFactory.getInstance();
        EntityMapping mapping = mappingFactory.getMap(MappingFactory.ADMIN_MAPPING);
        List<Object> list = jdbcTemplate.query(sql,mapping,string);
        return list;
    }

    @Override
    public boolean register(Admin admin) {
        String sql = "insert into admin(username,password) value(?,?)";
        int isRight = jdbcTemplate.update(sql,admin.getUsername(),admin.getPassword());
        return isRight==1;

    }

    @Override
    public boolean modify(Admin admin) {
        Admin ad = login(admin.getUsername(),admin.getPassword());
        String sql = "update admin set username=?,password=? where id=?";
        int isRight = jdbcTemplate.update(sql,admin.getUsername(),admin.getPassword(),ad.getId());
        return isRight==1;
    }

    @Override
    public boolean delete(Admin admin) {
        Admin ad = login(admin.getUsername(),admin.getPassword());
        String sql = "delete from admin where id=?";
        int isRight = jdbcTemplate.update(sql,ad.getId());
        return isRight==1;
    }

    public static void main(String[] args) {
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        JdbcTemplate jt =JdbcTemplate.getInstance();
        jt.setConnection(conn);
        AdminDaoImpl guestDao = new AdminDaoImpl();
        List<Object> list = guestDao.LikeQuery("o");
        for (int i = 0;i<list.size();i++){
            Admin guest = (Admin) list.get(i);
            System.out.println(guest.getUsername());
        }
    }
}
